#include <memory.h>
#include <stdio.h>
#include <sys/mman.h>

#include <fcntl.h>

#include <unistd.h>


int g_memFd = -1;
int *dmaBuff = NULL;
#define MAX_DMA_SIZE    1024
#define __REG(x)        (*((volatile unsigned int *)(x)))   
char devName[126];

void openMemDev()
{
    if( g_memFd == -1)
    {
        if((g_memFd = open(devName, O_RDWR | O_SYNC)) == -1)
        {
            printf("open /dev/mem error\n");
        }
    }
}


int mem_rw( char bRead,  unsigned int addr,  int value)  //init 
{
    int map_base;
    int addr_base =   addr & 0xfffff000;
    int addf_offset = addr & 0x00000fff;
    	openMemDev();
	if(dmaBuff == NULL)
		dmaBuff = malloc( MAX_DMA_SIZE );
	if( dmaBuff == NULL)
		{
		printf("error alloc dma size:%d \n",MAX_DMA_SIZE);
		}
printf("open mem:%x for %c , value:%d\n", addr_base, bRead, value);
    map_base = (int )mmap(0,4096, PROT_READ | PROT_WRITE, MAP_SHARED, g_memFd,  addr_base );  
    if( map_base == -1)
        goto erroResult;
  if( bRead == 'r' || bRead == 'R')
{
for( ; value -- ;)
{
      printf("addr:%x, value:%x\n", addr_base + addf_offset, __REG(map_base + addf_offset  ));
addf_offset  = addf_offset   + 4;
}
}
  else
      __REG(map_base + addf_offset  ) = value ;   
    munmap((void *)map_base, 4096);
return 0;
erroResult:
	printf("error: init \n" );
    return -1;
}

int main(int argc,char *argv[])
{
char bRead;
int value;
unsigned int addr;
if( argc < 2 )
{
	printf("name,dev (like:memdis /dev/mem) \n");
	return 0;
}
strcpy(devName , argv[1] );
printf(" enter r/w addr value for %s\n" , devName);
while(1 )
{
	printf("enter r/W\n");
fflush( stdin  );
   scanf("%c  ", &bRead  );
fflush( stdin );
printf(" enter   addr value \n");
 scanf("%x %d  ",  &addr, &value);
fflush( stdin  );
   if( mem_rw( bRead, addr, value) < 0)
      return;
} 


}

